package com.sqx.modules.orders.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.VipDetailsDao;
import com.sqx.modules.app.entity.*;
import com.sqx.modules.app.service.*;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.evaluate.entity.SysEvaluate;
import com.sqx.modules.evaluate.service.SysEvaluateService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.orders.dao.OrdersDao;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.entity.vo.OrderBroadcastVo;
import com.sqx.modules.orders.response.OrderAllResponse;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.pay.controller.app.AliPayController;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.WxService;
import com.sqx.modules.repairRecord.entity.RepairRecord;
import com.sqx.modules.repairRecord.service.RepairRecordService;
import com.sqx.modules.taking.dao.OrderTakingDao;
import com.sqx.modules.taking.entity.OrderTaking;
import com.sqx.modules.taking.service.OrderTakingService;
import com.sqx.modules.task.dao.HelpTakeDao;
import com.sqx.modules.task.entity.HelpOrder;
import com.sqx.modules.task.entity.HelpTake;
import com.sqx.modules.task.service.HelpOrderService;
import com.sqx.modules.task.service.HelpTakeService;
import com.sqx.modules.tbCoupon.entity.TbCouponUser;
import com.sqx.modules.tbCoupon.service.TbCouponUserService;
import com.sqx.modules.utils.AliPayOrderUtil;
import com.sqx.modules.utils.HttpClientUtil;
import com.sqx.modules.utils.SenInfoCheckUtil;
import com.sqx.modules.utils.excel.ExcelData;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {

    @Autowired
    private OrderTakingDao orderTakingDao;
    @Autowired
    private UserVipService userVipService;
    @Autowired
    private VipDetailsDao vipDetailsDao;
    @Autowired
    private PayDetailsDao payDetailsDao;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AliPayController aliPayController;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderTakingService orderTakingService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private WxService wxService;
    @Autowired
    private HelpTakeService takeService;
    @Autowired
    private ServiceTimeService serviceTimeService;
    @Autowired
    private SysEvaluateService evaluateService;
    @Autowired
    private HelpTakeDao takeDao;
    @Autowired
    private TbCouponUserService couponUserService;
    @Autowired
    private HelpOrderService helpOrderService;
    @Autowired
    private RepairRecordService repairRecordService;
    @Autowired
    private UserCertificationService userCertificationService;
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);

    @Override
    public int selectMyOrdersCount(Long userId, String time) {
        return baseMapper.selectMyOrdersCount(userId, time);
    }

    @Override
    public int selectTakeOrdersCount(Long userId, String time) {
        return baseMapper.selectTakeOrdersCount(userId, time);
    }

    @Override
    public Result updateOrdersAddress(Long ordersId, Long addressId) {
        Orders orders = baseMapper.selectById(ordersId);
        if ("0".equals(orders.getState())) {
            Address byId = addressService.getById(addressId);
            orders.setProvince(byId.getProvince());
            orders.setCity(byId.getCity());
            orders.setDistrict(byId.getDistrict());
            orders.setDetailsAddress(byId.getDetailsAddress());
            orders.setName(byId.getName());
            orders.setPhone(byId.getPhone());
            orders.setLatitude(byId.getLatitude());
            orders.setLongitude(byId.getLongitude());
            baseMapper.updateById(orders);
            return Result.success();
        }
        return Result.error("当前订单状态不允许修改地址！");
    }

    /**
     * 生成订单
     *
     * @param userId
     * @param id
     * @param couponId
     * @param khname
     * @param khphone
     * @return
     */
    @Override
    public Result generateOrder(Long userId, Long id, Long orderType, Long orderNumber, String remarks, Long addressId, String startTime, Long serviceTimeId, Long couponId, String khname, String khphone) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //判断订单类型
        if (orderType != null) {
            //创建订单模板
            Orders orders = new Orders();
            //查看会员信息
            UserVip userVip = userVipService.selectUserVipByUserId(userId);

            //接单
            if (orderType == 1) {
                //接单的订单
                OrderTaking orderTaking = orderTakingDao.selectById(id);
                UserEntity shUser = userService.getById(orderTaking.getUserId());
                //接单的订单是否存在
                if (orderTaking == null || orderTaking.getIsdelete() == 1) {
                    return Result.error("订单不存在，请刷新页面后重试！");
                }
                Integer counts = baseMapper.selectCount(new QueryWrapper<Orders>().in("state", 1, 2, 4).eq("order_taking_user_id", orderTaking.getUserId()).eq("order_taking_id", id).eq("start_time", startTime));
                ServiceTime serviceTime = serviceTimeService.getById(serviceTimeId);
                if (serviceTime.getNum() <= counts) {
                    return Result.error("当前时段预约已满，请您更换其他时间段！");
                }
                orders.setServiceTimeId(serviceTimeId);
                //设置订单编号
                orders.setOrdersNo(AliPayOrderUtil.createOrderId());
                //设置用户id
                orders.setUserId(userId);
                orders.setOrderTakingUserId(orderTaking.getUserId());
                orders.setStartTime(startTime);
                //设置接单id
                orders.setOrderTakingId(id);
                //设置订单状态
                orders.setState("0");
                //设置创建时间
                orders.setCreateTime(df.format(new Date()));
                //设置更新时间
                orders.setUpdateTime(df.format(new Date()));
                //设置订单种类
                orders.setOrdersType(orderType);
                //用户类型
                orders.setType((long) 1);
                //服务方式
                orders.setServiceMethod(orderTaking.getServiceMethod());
                //地址
                if(addressId != null){
                    Address byId = addressService.getById(addressId);
                    orders.setProvince(byId.getProvince());
                    orders.setCity(byId.getCity());
                    orders.setDistrict(byId.getDistrict());
                    orders.setDetailsAddress(byId.getDetailsAddress());
                    orders.setName(byId.getName());
                    orders.setPhone(byId.getPhone());
                    orders.setLatitude(byId.getLatitude());
                    orders.setLongitude(byId.getLongitude());
                }
                else {
                    //orders.setDetailsAddress(shUser.getAddress());
                    orders.setName(khname);
                    orders.setPhone(khphone);
                }
                //订单数量
                if (orderNumber != null) {
                    try {
                        if (userVip != null && df.parse(userVip.getEndTime()).getTime() > System.currentTimeMillis() && userVip.getIsVip() == 1) {
                            orders.setType((long) 1);
                            BigDecimal money = orderTaking.getMemberMoney();
                            BigDecimal moneys = money.multiply(BigDecimal.valueOf(orderNumber));
                            //设置支付金额
                            orders.setPayMoney(moneys);
                        } else {
                            orders.setType((long) 2);
                            BigDecimal money = orderTaking.getMoney();
                            BigDecimal nmoney = money.multiply(BigDecimal.valueOf(orderNumber));
                            //设置支付金额
                            orders.setPayMoney(nmoney);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                        log.error("生成订单会员价格出异常：" + e.getMessage(), e);
                        orders.setType((long) 2);
                        BigDecimal money = orderTaking.getMoney();
                        BigDecimal nmoney = money.multiply(BigDecimal.valueOf(orderNumber));
                        //设置支付金额
                        orders.setPayMoney(nmoney);
                    }
                    //设置订单数量
                    orders.setOrderNumber(orderNumber);
                    //设置备注
                    orders.setRemarks(remarks);
                    //设置假射出状态
                    orders.setIsdelete((long) 0);
                    int code = (int) ((Math.random() * 9 + 1) * 1000);
                    orders.setCode(String.valueOf(code));
                    //优惠券代码逻辑
                    if (couponId != null) {
                        TbCouponUser tbCouponUser = couponUserService.getById(couponId);
                        if (tbCouponUser == null) {
                            return Result.error("你未持有当前优惠券");
                        }
                        if (tbCouponUser.getStatus() == 1) {
                            return Result.error("当前优惠券已使用");
                        }
                        if (tbCouponUser.getStatus() == 2) {
                            return Result.error("当前优惠券已失效");
                        }
                        //如果订单金额大于优惠券最小订单金额
                        if (orders.getPayMoney().compareTo(tbCouponUser.getMinMoney()) >= 0) {
                            //写入使用了优惠券之后的订单金额
                            orders.setPayMoney(orders.getPayMoney().subtract(tbCouponUser.getMoney()));
                            tbCouponUser.setStatus(1);
                            tbCouponUser.setEmployTime(new Date());
                            couponUserService.updateById(tbCouponUser);
                        } else {
                            return Result.error("订单金额不满足最低满减金额");
                        }
                    }
                    orders.setCouponId(couponId);
                    baseMapper.insert(orders);
                    return Result.success().put("data", orders);
                } else {
                    return Result.error("订单数量为空！订单生成失败");
                }

            } else {
                //会员
                //设置订单编号
                orders.setOrdersNo(AliPayOrderUtil.createOrderId());
                //设置用户id
                orders.setUserId(userId);
                //设置要开通的会员类型id
                orders.setVipDetailsId(id);
                //查询会员支付价钱
                VipDetails vipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("id", id));
                //设置订单金额
                orders.setPayMoney(vipDetails.getMoney());
                //设置订单状态 待支付
                orders.setState("0");
                //设置创建时间
                orders.setCreateTime(df.format(new Date()));
                //设置更新时间
                orders.setUpdateTime(df.format(new Date()));
                orders.setIsdelete((long) 0);
                //设置订单种类
                orders.setOrdersType(orderType);
                baseMapper.insert(orders);
                return Result.success().put("data", orders);
            }
        } else {
            return Result.error("订单类型异常，请刷新页面后重试！");
        }
    }

    @Override
    public Result selectMyOrder(Long userId, IPage iPage, String status, Long orderTakingUserId) {

        return Result.success().put("data", new PageUtils(baseMapper.selectMyOrder(iPage, userId, status, orderTakingUserId)));
    }

    @Override
    public Result investOrder(Long userId, Double money, Integer classify) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PayDetails payDetails = new PayDetails();
        //分类（ 1app微信 2微信公众号 3微信小程序 4支付宝）
        payDetails.setClassify(classify);
        //订单编号
        payDetails.setOrderId(AliPayOrderUtil.createOrderId());
        //金额
        payDetails.setMoney(money);
        //用户id
        payDetails.setUserId(userId);
        //状态0待支付 1支付成功 2失败
        payDetails.setState(0);
        //创建时间
        payDetails.setCreateTime(simpleDateFormat.format(new Date()));
        payDetailsDao.insert(payDetails);
        return Result.success();
    }


    @Override
    public Result cancelOrder(Long id, String status, String code, String startServiceImg, String endServiceImg, BigDecimal money,
                              String startServiceLongitude, String startServiceLatitude,
                              String endServiceLongitude, String endServiceLatitude, Integer type) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            return cancelOrders(id, status, code, startServiceImg, endServiceImg, money, startServiceLongitude,
                    startServiceLatitude, endServiceLongitude, endServiceLatitude, type);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改订单异常：" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Transactional
    public Result cancelOrders(Long id, String status, String code, String startServiceImg, String endServiceImg, BigDecimal money,
                               String startServiceLongitude, String startServiceLatitude,
                               String endServiceLongitude, String endServiceLatitude, Integer type) {
        Orders orders = baseMapper.selectById(id);
        DecimalFormat df=new DecimalFormat("0.00");
        log.error("开始经纬度：" + startServiceLongitude + "----------" + startServiceLatitude);
        log.error("结束经纬度：" + endServiceLongitude + "----------" + endServiceLatitude);
        if (orders != null) {
            if ("4".equals(orders.getState())) {
                if ("1".equals(status)) {
                    OrderTaking taking = orderTakingService.getById(orders.getOrderTakingId());
                    if (startServiceImg.split(",").length < 4) {
                        return Result.error("开始服务请上传最少4张图片");
                    }

                    orders.setState(status);
                    orders.setStartServiceTime(DateUtils.format(new Date()));
                    orders.setStartServiceImg(startServiceImg);
                    orders.setStartServiceLatitude(startServiceLatitude);
                    orders.setStartServiceLongitude(startServiceLongitude);
                    String startAddress = null;
                    if (type != 2) {
                        String way = commonInfoService.findOne(414).getValue();
                        if ("1".equals(way)) {
                            CommonInfo one = commonInfoService.findOne(217);
                            String url = "https://apis.map.qq.com/ws/geocoder/v1/";
                            Map<String, String> maps = new HashMap<>();
                            maps.put("location", startServiceLatitude + "," + startServiceLongitude);
                            maps.put("key", one.getValue());
                            String data = HttpClientUtil.doGet(url, maps);
                            JSONObject jsonObject = JSON.parseObject(data);
                            String statuss = jsonObject.getString("status");
                            if ("0".equals(statuss)) {
                                JSONObject result = jsonObject.getJSONObject("result");
                                startAddress = result.getString("address");
                            } else {
                                log.error("转换失败！！！原因:" + jsonObject.getString("message"));
                            }
                        } else {
                            String value = commonInfoService.findOne(415).getValue();
                            String url = "http://api.tianditu.gov.cn/geocoder";
                            Map<String, String> param = new HashMap<>();
                            JSONObject postStr = new JSONObject();
                            postStr.put("lon", startServiceLongitude);
                            postStr.put("lat", startServiceLatitude);
                            postStr.put("ver", "1");
                            param.put("postStr", postStr.toJSONString());
                            param.put("type", "geocode");
                            param.put("tk", value);
                            String s = HttpClientUtil.doGet(url, param);
                            JSONObject jsonObject = JSONObject.parseObject(s);
                            String statuss = jsonObject.getString("status");
                            if ("0".equals(statuss)) {
                                JSONObject result = jsonObject.getJSONObject("result");
                                startAddress = result.getString("formatted_address");
                            } else {
                                log.error("转换失败！！！原因:" + jsonObject.getString("msg"));
                            }
                        }
                    }

                    orders.setStartAddress(startAddress);

                    UserEntity userEntity = userService.getById(orders.getUserId());

                    String value = commonInfoService.findOne(312).getValue();
                    if (StringUtils.isNotBlank(userEntity.getOpenId())) {
                        List<String> msgList = new ArrayList<>();
                        msgList.add(orders.getOrdersNo());
                        msgList.add(taking.getOrderTakingArea());
                        msgList.add("正在进行");
                        msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                        msgList.add("师傅已开始服务");
                        SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), value, 2, msgList, 4);
                    }
                } else if ("3".equals(status)) {
                    if ("0".equals(orders.getState())) {
                        orders.setState(status);
                        return Result.upStatus(baseMapper.updateById(orders));
                    }
                    if(orders.getCouponId()!=null){
                        TbCouponUser tbCouponUser = new TbCouponUser();
                        tbCouponUser.setId(orders.getCouponId());
                        tbCouponUser.setStatus(0);
                        couponUserService.updateById(tbCouponUser);
                    }

                    if (money == null) {
                        money = orders.getPayMoney();
                    }
                    if (orders.getPayWay() == null || orders.getPayWay() == 1) {
                        //退款
                        userMoneyService.updateMoney(1, orders.getUserId(), money);
                    } else if (orders.getPayWay() == 2) {
                        //微信
                        boolean refund = wxService.refund(orders.getOrdersNo(), money);
                        if (!refund) {
                            return Result.error("退款失败，请联系客服处理！");
                        }
                    } else {
                        //支付宝
                        String data = aliPayController.alipayRefund(orders.getOrdersNo(), money);
                        if (StringUtils.isNotBlank(data)) {
                            log.error(data);
                            JSONObject jsonObject = JSON.parseObject(data);
                            JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                            String code1 = alipay_trade_refund_response.getString("code");
                            if (!"10000".equals(code1)) {
                                return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                            }
                        } else {
                            return Result.error("退款失败！");
                        }
                    }
                    orders.setState(status);

                    UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                    userMoneyDetails.setUserId(orders.getUserId());
                    userMoneyDetails.setTitle("订单退款：" + orders.getOrdersNo());
                    userMoneyDetails.setContent("订单已原路退款：" + money);
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setMoney(money);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    userMoneyDetails.setCreateTime(sdf.format(new Date()));
                    userMoneyDetailsService.save(userMoneyDetails);

                    //小程序订阅号消息推送
                    CommonInfo one = commonInfoService.findOne(236);
                    List<String> retList = new ArrayList<>();
                    retList.add(orders.getOrdersNo());//订单号
                    retList.add(String.valueOf(money));//退款金额
                    retList.add("您的订单已取消，金额已原路退还");//温馨提示
                    UserEntity userEntity = userService.selectUserById(orders.getUserId());
                    if (StringUtils.isNotEmpty(userEntity.getOpenId())) {
                        SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), 2, retList, 2);
                    }
                    if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                        userService.pushToSingle(userMoneyDetails.getTitle(), userMoneyDetails.getContent(), userEntity.getClientid());
                    }
                    OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId());
                    if (orders.getStaffUserId() != null) {
                        String masterSend = commonInfoService.findOne(313).getValue();
                        UserEntity masterEntity = userService.getById(orders.getStaffUserId());
                        if (StringUtils.isNotBlank(masterEntity.getMasterOpenId())) {
                            List<String> cancelList = new ArrayList<>();
                            cancelList.add(orders.getOrdersNo());
                            cancelList.add(orderTaking.getOrderTakingArea());
                            cancelList.add("订单已取消");
                            cancelList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                            cancelList.add("用户已取消订单");
                            SenInfoCheckUtil.sendMasterMsg(masterEntity.getMasterOpenId(), masterSend, cancelList, 4);
                        }
                    }
                    String shopSend = commonInfoService.findOne(623).getValue();
                    userEntity = userService.getById(orderTaking.getUserId());
                    if (StringUtils.isNotBlank(userEntity.getShopOpenId())) {
                        List<String> shoplList = new ArrayList<>();
                        shoplList.add(orders.getOrdersNo());
                        shoplList.add(orderTaking.getOrderTakingArea());
                        shoplList.add("订单已取消");
                        shoplList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                        shoplList.add("用户已取消订单");
                        SenInfoCheckUtil.sendShopMsg(userEntity.getShopOpenId(), shopSend, null, shoplList, 7);
                    }


                }
            }
            if ("1".equals(orders.getState())) {

                if ("2".equals(status)) {
                    if (!code.equals(orders.getCode())) {
                        return Result.error("确认码不正确！");
                    }
                    orders.setEndServiceImg(endServiceImg);
                    orders.setEndServiceTime(DateUtils.format(new Date()));
                    orders.setEndServiceLatitude(endServiceLatitude);
                    orders.setEndServiceLongitude(endServiceLongitude);

                    String endAddress = null;
                    String way = commonInfoService.findOne(414).getValue();
                    if (StringUtils.isNotBlank(endServiceLatitude) && StringUtils.isNotBlank(endServiceLongitude)) {
                        if ("1".equals(way)) {
                            CommonInfo one = commonInfoService.findOne(217);
                            String url = "https://apis.map.qq.com/ws/geocoder/v1/";
                            Map<String, String> maps = new HashMap<>();
                            maps.put("location", endServiceLatitude + "," + endServiceLongitude);
                            maps.put("key", one.getValue());
                            String data = HttpClientUtil.doGet(url, maps);
                            JSONObject jsonObject = JSON.parseObject(data);
                            String statuss = jsonObject.getString("status");
                            if ("0".equals(statuss)) {
                                JSONObject result = jsonObject.getJSONObject("result");
                                endAddress = result.getString("address");
                            } else {
                                log.error("转换失败！！！原因:" + jsonObject.getString("message"));
                            }
                        } else {
                            String value = commonInfoService.findOne(415).getValue();
                            String url = "http://api.tianditu.gov.cn/geocoder";
                            Map<String, String> param = new HashMap<>();
                            JSONObject postStr = new JSONObject();
                            postStr.put("lon", endServiceLongitude);
                            postStr.put("lat", endServiceLatitude);
                            postStr.put("ver", "1");
                            param.put("postStr", postStr.toJSONString());
                            param.put("type", "geocode");
                            param.put("tk", value);
                            String s = HttpClientUtil.doGet(url, param);
                            JSONObject jsonObject = JSONObject.parseObject(s);
                            String statuss = jsonObject.getString("status");
                            if ("0".equals(statuss)) {
                                JSONObject result = jsonObject.getJSONObject("result");
                                endAddress = result.getString("formatted_address");
                            } else {
                                log.error("转换失败！！！原因:" + jsonObject.getString("msg"));
                            }
                        }
                    }
                    orders.setEndAddress(endAddress);

                    //完成订单
                    OrderTaking orderTaking = orderTakingDao.selectById(orders.getOrderTakingId());
                    Integer ordersCount = baseMapper.selectCount(new QueryWrapper<Orders>().eq("order_taking_id", orders.getOrderTakingId()).eq("state", 2).eq("orders_type", 1));
                    ordersCount += baseMapper.selectCount(new QueryWrapper<Orders>().eq("order_taking_id", orders.getOrderTakingId()).eq("state", 1).eq("orders_type", 1));
                    orderTaking.setCount(ordersCount);
                    orderTaking.setId(orders.getOrderTakingId());
                    orderTaking.setSalesNum((orderTaking.getSalesNum() == null ? 0 : orderTaking.getSalesNum()) + orders.getOrderNumber().intValue());
                    orderTakingService.updateById(orderTaking);
                    BigDecimal add = orders.getPayMoney();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String time = sdf.format(new Date());
                    BigDecimal refundMoney=BigDecimal.ZERO;
                    if(orders.getRefundMoney()!=null){
                        refundMoney=orders.getRefundMoney();
                    }
                    BigDecimal ordersMoney = orders.getPayMoney().subtract(refundMoney);
                    BigDecimal sumMoney = ordersMoney;
                    List<RepairRecord> list = repairRecordService.list(new QueryWrapper<RepairRecord>().eq("order_no", orders.getOrdersNo()).eq("order_type", 2));
                    for (RepairRecord record:list){
                        refundMoney=BigDecimal.ZERO;
                        if(record.getRefundMoney()!=null){
                            refundMoney=record.getRefundMoney();
                        }
                        BigDecimal recordMoney = record.getPayMoney().subtract(refundMoney);
                        sumMoney=sumMoney.add(recordMoney);
                    }
                    add=sumMoney;
                    //判断是否开启分销
                    String value = commonInfoService.findOne(209).getValue();
                    if ("是".equals(value)) {
                        //分销
                        UserEntity userEntity = userService.selectUserById(orderTaking.getUserId());
                        //陪玩官
                        BigDecimal peiMoney;
                        if (userEntity.getRate().doubleValue() == 0 || userEntity.getRate().doubleValue() < 0) {
                            peiMoney = add;
                        } else {
                            peiMoney = add.multiply(userEntity.getRate());
                        }
                        orders.setRate(peiMoney);
                        userMoneyService.updateMoney(1, orderTaking.getUserId(), peiMoney);
                        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                        userMoneyDetails.setUserId(orderTaking.getUserId());
                        userMoneyDetails.setTitle("订单完成：" + orders.getOrdersNo());

                        userMoneyDetails.setContent("订单完成，到账金额：" + df.format(peiMoney));
                        userMoneyDetails.setType(1);
                        userMoneyDetails.setMoney(peiMoney);
                        userMoneyDetails.setCreateTime(time);
                        userMoneyDetailsService.save(userMoneyDetails);
                        //判断订单是师傅接单还是员工接单
                        if (orders.getStaffUserId() != null) {
                            String masterSend = commonInfoService.findOne(313).getValue();
                            userEntity = userService.getById(orders.getStaffUserId());
                            if (StringUtils.isNotBlank(userEntity.getMasterOpenId())) {
                                List<String> msgList = new ArrayList<>();
                                msgList.add(orders.getOrdersNo());
                                msgList.add(orderTaking.getOrderTakingArea());
                                msgList.add("订单完成");
                                msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                                msgList.add("订单完成,到账金额：" + df.format(add));
                                SenInfoCheckUtil.sendMasterMsg(userEntity.getMasterOpenId(), masterSend, msgList, 4);
                            }
                        }
                        String shopSend = commonInfoService.findOne(623).getValue();
                        userEntity = userService.getById(orderTaking.getUserId());
                        if (StringUtils.isNotBlank(userEntity.getShopOpenId())) {
                            List<String> msgList = new ArrayList<>();
                            msgList.add(orders.getOrdersNo());
                            msgList.add(orderTaking.getOrderTakingArea());
                            msgList.add("订单完成");
                            msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                            msgList.add("订单完成,到账金额：" + df.format(add));
                            SenInfoCheckUtil.sendShopMsg(userEntity.getShopOpenId(),shopSend,null,  msgList, 7);
                        }
                        //直属
                        UserEntity zhiUser = userService.queryByInvitationCode(userEntity.getInviterCode());
                        if (zhiUser != null) {
                            if (zhiUser.getZhiRate().doubleValue() != 0 && zhiUser.getZhiRate().doubleValue() > 0) {
                                peiMoney = add.multiply(zhiUser.getZhiRate());
                                orders.setZhiRate(peiMoney);
                                orders.setZhiUserId(zhiUser.getUserId());
                                userMoneyService.updateMoney(1, zhiUser.getUserId(), peiMoney);
                                userMoneyDetails = new UserMoneyDetails();
                                userMoneyDetails.setUserId(zhiUser.getUserId());
                                userMoneyDetails.setTitle("一级佣金订单完成：" + orders.getOrdersNo());
                                userMoneyDetails.setContent("一级佣金订单完成，到账金额：" + df.format(peiMoney));
                                userMoneyDetails.setType(1);
                                userMoneyDetails.setMoney(peiMoney);
                                userMoneyDetails.setCreateTime(time);
                                userMoneyDetailsService.save(userMoneyDetails);

                                //非直属
                                UserEntity feiUser = userService.queryByInvitationCode(zhiUser.getInviterCode());
                                if (feiUser != null) {
                                    if (feiUser.getFeiRate().doubleValue() != 0 && feiUser.getFeiRate().doubleValue() > 0) {
                                        peiMoney = add.multiply(feiUser.getFeiRate());
                                        orders.setFeiRate(peiMoney);
                                        orders.setFeiUserId(feiUser.getUserId());
                                        userMoneyService.updateMoney(1, feiUser.getUserId(), peiMoney);
                                        userMoneyDetails = new UserMoneyDetails();
                                        userMoneyDetails.setUserId(feiUser.getUserId());
                                        userMoneyDetails.setTitle("二级佣金订单完成：" + orders.getOrdersNo());
                                        userMoneyDetails.setContent("二级佣金订单完成，到账金额：" + df.format(peiMoney));
                                        userMoneyDetails.setType(1);
                                        userMoneyDetails.setMoney(peiMoney);
                                        userMoneyDetails.setCreateTime(time);
                                        userMoneyDetailsService.save(userMoneyDetails);
                                    }
                                }
                            }
                        }
                    } else {
                        orders.setRate(add);
                        userMoneyService.updateMoney(1, orderTaking.getUserId(), add);
                        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                        userMoneyDetails.setUserId(orderTaking.getUserId());
                        userMoneyDetails.setTitle("订单完成：" + orders.getOrdersNo());
                        userMoneyDetails.setContent("订单完成，到账金额：" + add);
                        userMoneyDetails.setType(1);
                        userMoneyDetails.setMoney(add);
                        userMoneyDetails.setCreateTime(time);
                        userMoneyDetailsService.save(userMoneyDetails);
                        String masterSend = commonInfoService.findOne(313).getValue();

                        //判断订单是师傅接单还是员工接单
                        if (orders.getStaffUserId() != null) {
                            UserEntity userEntity = userService.getById(orders.getStaffUserId());
                            if (StringUtils.isNotBlank(userEntity.getMasterOpenId())) {
                                List<String> msgList = new ArrayList<>();
                                msgList.add(orders.getOrdersNo());
                                msgList.add(orderTaking.getOrderTakingArea());
                                msgList.add("订单完成");
                                msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                                msgList.add("订单完成,到账金额：" + df.format(add));
                                SenInfoCheckUtil.sendMasterMsg(userEntity.getMasterOpenId(), masterSend, msgList, 4);
                            }
                        }
                        String shopSend = commonInfoService.findOne(623).getValue();
                        UserEntity userEntity = userService.getById(orderTaking.getUserId());
                        if (StringUtils.isNotBlank(userEntity.getShopOpenId())) {
                            List<String> msgList = new ArrayList<>();
                            msgList.add(orders.getOrdersNo());
                            msgList.add(orderTaking.getOrderTakingArea());
                            msgList.add("订单完成");
                            msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                            msgList.add("订单完成,到账金额：" + df.format(add));
                            SenInfoCheckUtil.sendShopMsg(userEntity.getMasterOpenId(), shopSend,null, msgList, 7);
                        }

                    }
                    BigDecimal pingRate = orders.getPayMoney().subtract(orders.getRate());
                    if (orders.getZhiRate() != null) {
                        pingRate = pingRate.subtract(orders.getZhiRate());
                    }
                    if (orders.getFeiRate() != null) {
                        pingRate = pingRate.subtract(orders.getFeiRate());
                    }
                    orders.setPingRate(pingRate);
                    orders.setState(status);
                    baseMapper.updateById(orders);
                    OrderTaking taking = orderTakingService.getById(orders.getOrderTakingId());
                    UserEntity userEntity = userService.getById(orders.getUserId());
                    String userSend = commonInfoService.findOne(312).getValue();
                    if (StringUtils.isNotBlank(userEntity.getOpenId())) {
                        List<String> msgList = new ArrayList<>();
                        msgList.add(orders.getOrdersNo());
                        msgList.add(taking.getOrderTakingArea());
                        msgList.add("订单已完成");
                        msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                        msgList.add("师傅已完成订单");
                        SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), userSend, 2, msgList, 4);
                    }
                }

            } else if ("0".equals(orders.getState())) {
                orders.setState("3");
                if(orders.getCouponId()!=null){
                    TbCouponUser tbCouponUser = new TbCouponUser();
                    tbCouponUser.setId(orders.getCouponId());
                    tbCouponUser.setStatus(0);
                    couponUserService.updateById(tbCouponUser);
                }
            }
            baseMapper.updateById(orders);
            return Result.success();

        } else {
            return Result.error("订单不存在！");
        }
    }


    @Override
    public Result deleteOrder(Long id) {
        Orders orders = baseMapper.selectById(id);
        if (orders != null) {
            orders.setIsdelete((long) 1);
            baseMapper.update(orders, new QueryWrapper<Orders>().eq("orders_id", id));
            return Result.success();
        } else {
            return Result.error("订单不存在！");
        }
    }

    @Override
    public Result queryOrders(Long id) {
        Orders orders = baseMapper.selectById(id);
        List<RepairRecord> repairRecord = repairRecordService.list(new QueryWrapper<RepairRecord>().eq("order_type", 2).eq("order_no", orders.getOrdersNo()));
        if (repairRecord.size() > 0) {
            orders.setIsRepair(1);
        } else {
            orders.setIsRepair(0);
        }
        TbCouponUser tbCouponUser = couponUserService.getById(orders.getCouponId());
        if (tbCouponUser != null) {
            orders.setCouponMoney(tbCouponUser.getMoney());
        }
        OrderTaking orderTaking = orderTakingDao.selectById(orders.getOrderTakingId());
        if (orderTaking != null) {
            if (orders.getType() == 1) {
                orderTaking.setOldMoney(orderTaking.getMemberMoney());
            } else {
                orderTaking.setOldMoney(orderTaking.getMoney());
            }
            orders.setOrderTaking(orderTaking);
            UserEntity userEntity = userDao.selectById(orderTaking.getUserId());
            orders.setUser(userEntity);
        }
        SysEvaluate evaluate = evaluateService.getOne(new QueryWrapper<SysEvaluate>().eq("indent_number", orders.getOrdersNo()));
        if (evaluate != null) {
            orders.setSysEvaluate(evaluate);
        }
        return Result.success().put("data", orders);
    }

    @Override
    public Result queryOrdersAll(Long page, Long limit, Long type, String userName, String ordersUserName, Long status, Long userId, String ordersNo, String startTime, String endTIme, Long orderTakingUserId, String companyName) {
        IPage<Orders> iPage = new Page<>(page, limit);
        return Result.success().put("data", new PageUtils(baseMapper.queryOrdersAll(iPage, type, userName, ordersUserName, status, userId, ordersNo, startTime, endTIme, orderTakingUserId, companyName)));
    }

    @Override
    public ExcelData ordersListExcel(Long type, String name, Long status, Long userId, String ordersNo, String startTime, String endTIme) {
        if (StringUtils.isNotEmpty(name)) {
            name = "%" + name + "%";
        }
        List<OrderAllResponse> orderAllResponses = baseMapper.ordersListExcel(type, name, status, userId, ordersNo, startTime, endTIme);
        ExcelData data = new ExcelData();
        data.setName("订单列表");
        List<String> titles = new ArrayList();
        titles.add("编号");
        titles.add("接单用户");
        titles.add("下单用户");
        titles.add("订单编号");
        titles.add("订单类型");
        titles.add("标题");
        titles.add("发布价格");
        titles.add("普通用户价格");
        titles.add("会员价格");
        titles.add("商家佣金");
        titles.add("一级佣金");
        titles.add("二级佣金");
        titles.add("平台金额");
        titles.add("时长");
        titles.add("单位");
        titles.add("支付金额");
        titles.add("上门时间");
        titles.add("备注");
        titles.add("收货码");
        titles.add("订单状态");
        titles.add("创建时间");
        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList();
        for (OrderAllResponse orderAllResponse : orderAllResponses) {
            List<Object> row = new ArrayList();
            row.add(orderAllResponse.getOrdersId());
            row.add(orderAllResponse.getUserName());
            row.add(orderAllResponse.getOrdersUserName());
            row.add(orderAllResponse.getOrdersNo());
            if (orderAllResponse.getOrdersType() == 1) {
                row.add("服务订单");
            } else {
                row.add("会员订单");
            }
            row.add(orderAllResponse.getMyLevel() == null ? "" : orderAllResponse.getMyLevel());
            row.add(orderAllResponse.getOldMoney() == null ? "" : orderAllResponse.getOldMoney());
            row.add(orderAllResponse.getMoney() == null ? "" : orderAllResponse.getMoney());
            row.add(orderAllResponse.getMemberMoney() == null ? "" : orderAllResponse.getMemberMoney());
            row.add(orderAllResponse.getRate() == null ? 0 : orderAllResponse.getRate());
            row.add(orderAllResponse.getZhiRate() == null ? 0 : orderAllResponse.getZhiRate());
            row.add(orderAllResponse.getFeiRate() == null ? 0 : orderAllResponse.getFeiRate());
            row.add(orderAllResponse.getPingRate() == null ? 0 : orderAllResponse.getPingRate());
            row.add(orderAllResponse.getOrderNumber() == null ? "" : orderAllResponse.getOrderNumber());
            row.add(orderAllResponse.getUnit() == null ? "" : orderAllResponse.getUnit());
            row.add(orderAllResponse.getPayMoney() == null ? "" : orderAllResponse.getPayMoney());
            row.add(orderAllResponse.getStartTime() == null ? "" : orderAllResponse.getStartTime());
            row.add(orderAllResponse.getRemarks() == null ? "" : orderAllResponse.getRemarks());
            row.add(orderAllResponse.getCode() == null ? "" : orderAllResponse.getCode());
            if (orderAllResponse.getState() == 0) {
                row.add("待支付");
            } else if (orderAllResponse.getState() == 1) {
                row.add("进行中");
            } else if (orderAllResponse.getState() == 2) {
                row.add("已完成");
            } else if (orderAllResponse.getState() == 3) {
                row.add("已退款");
            } else if (orderAllResponse.getState() == 4) {
                row.add("待服务");
            } else {
                row.add("未知");
            }
            row.add(orderAllResponse.getCreateTime() == null ? "" : orderAllResponse.getCreateTime());
            rows.add(row);
        }
        data.setRows(rows);
        return data;
    }


    @Override
    public Result selectMyTakeOrders(Integer page, Integer limit, Long userId, Integer status, Long staffUserId, String name, String phone, String startTime, String staffUserName, String ordersNo) {
        return Result.success().put("data", new PageUtils(baseMapper.selectMyTakeOrders(new Page<Map<String, Object>>(page, limit), userId, status, staffUserId, name, phone, startTime, staffUserName, ordersNo)));
    }


    @Override
    public Result selectStaffUserOrders(Integer page, Integer limit, Long userId, Integer status, String name, String phone, String startTime, String ordersNo, Long orderTakingUserId) {
        return Result.success().put("data", new PageUtils(baseMapper.selectStaffUserOrders(new Page<Map<String, Object>>(page, limit), userId, status, name, phone, startTime, ordersNo, orderTakingUserId)));
    }

    @Override
    public Result payMoney(Long ordersId) {
        Orders orders = baseMapper.selectById(ordersId);
        if (orders != null) {
            OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId());
            Integer counts = baseMapper.selectCount(new QueryWrapper<Orders>().in("state", 1, 2, 4).eq("order_taking_user_id", orderTaking.getUserId()).eq("order_taking_id", orderTaking.getId()).eq("start_time", orders.getStartTime()));
            ServiceTime serviceTime = serviceTimeService.getById(orders.getServiceTimeId());
            if (serviceTime.getNum() <= counts) {
                return Result.error("当前时段预约已满，请您更换其他时间段！");
            }
            UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
            if (userMoney.getMoney().doubleValue() >= orders.getPayMoney().doubleValue()) {
                UserEntity userEntity = userService.selectUserById(orders.getUserId());

                userMoneyService.updateMoney(2, orders.getUserId(), orders.getPayMoney());
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                userMoneyDetails.setMoney(orders.getPayMoney());
                userMoneyDetails.setUserId(orders.getUserId());
                userMoneyDetails.setContent("支付订单：" + orders.getOrdersNo());
                userMoneyDetails.setTitle("下单成功");
                userMoneyDetails.setType(2);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setContent("订单下单成功：" + orders.getOrdersNo());
                messageInfo.setTitle("订单通知");
                messageInfo.setState(String.valueOf(4));
                messageInfo.setUserName(userEntity.getUserName());
                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                messageInfo.setCreateAt(simpleDateFormat.format(new Date()));
                messageInfo.setIsSee("0");
                messageService.saveBody(messageInfo);
                if (StringUtil.isNotBlank(userEntity.getClientid())) {
                    userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid());
                }
                String value = commonInfoService.findOne(312).getValue();
                if (StringUtils.isNotBlank(userEntity.getOpenId())) {
                    List<String> msgList = new ArrayList<>();
                    msgList.add(orders.getOrdersNo());
                    msgList.add(orderTaking.getOrderTakingArea());
                    msgList.add("订单已付款");
                    msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                    msgList.add("付款金额:" + orders.getPayMoney());
                    SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), value, 2, msgList, 4);
                }
                String userName = userEntity.getUserName();
                orders.setState("4");
                orders.setIsRemind(0);
                orders.setPayWay(1);
                baseMapper.updateById(orders);

                userEntity = userService.selectUserById(orderTaking.getUserId());
                MessageInfo messageInfos = new MessageInfo();
                messageInfos.setContent("订单接单成功：" + orders.getOrdersNo());
                messageInfos.setTitle("订单通知");
                messageInfos.setState(String.valueOf(6));
                messageInfos.setUserName(userEntity.getUserName());
                messageInfos.setUserId(String.valueOf(userEntity.getUserId()));
                messageInfos.setCreateAt(simpleDateFormat.format(new Date()));
                messageInfos.setIsSee("0");
                messageService.saveBody(messageInfos);
                if (StringUtil.isNotBlank(userEntity.getClientid())) {
                    userService.pushToSingle(messageInfos.getTitle(), messageInfos.getContent(), userEntity.getClientid());
                }


                //小程序订阅号消息推送
                CommonInfo one = commonInfoService.findOne(235);
                List<String> msgList = new ArrayList<>();
                msgList.add(orders.getOrdersNo());//订单号
                if (orderTaking.getGameId().length() > 15) {
                    orderTaking.setGameId(orderTaking.getGameId().substring(0, 15) + "...");
                }
                msgList.add(orderTaking.getGameId());//商品名称
                msgList.add(String.valueOf(orders.getOrderNumber()));//商品数量
                msgList.add(orders.getCreateTime());//下单时间
                msgList.add(userName);//客户名称

                UserEntity shopEntity = userService.getById(orders.getOrderTakingUserId());
                if (StringUtils.isNotEmpty(shopEntity.getShopOpenId())) {
                    SenInfoCheckUtil.sendShopMsg(shopEntity.getShopOpenId(), one.getValue(), null, msgList, 1);
                }

                messageInfo = new MessageInfo();
                messageInfo.setTitle("订单通知");
                messageInfo.setState(String.valueOf(10));
                messageInfo.setCreateAt(simpleDateFormat.format(new Date()));
                messageInfo.setIsSee("0");
                messageService.saveBody(messageInfo);

                return Result.success();
            } else {
                return Result.error("账户不足，请充值！");
            }
        } else {
            return Result.error("订单不存在，请刷新后重试！");
        }
    }

    @Override
    public PageUtils incomeAnalysisOrders(Integer page, Integer limit, String time, Integer flag) {
        Page<Map<String, Object>> pages = new Page<>(page, limit);
        return new PageUtils(baseMapper.incomeAnalysisOrders(pages, time, flag));
    }

    @Override
    public Integer getOrdersRemind(Long userId) {
        return baseMapper.getOrdersRemind(userId);
    }

    @Override
    public int updateOrdersIsRemind(Long userId) {
        return baseMapper.updateOrdersIsRemind(userId);
    }

    @Override
    public Result selectTeamOrdersList(Integer page, Integer limit, Long userId, Integer type, Integer status) {
        return Result.success().put("data", new PageUtils(baseMapper.selectTeamOrdersList(new Page<>(page, limit), userId, type, status)));
    }

    @Override
    public Result selectTeamUserList(Integer page, Integer limit, String invitationCode, Integer type, Long userId) {
        return Result.success().put("data", new PageUtils(baseMapper.selectTeamUserList(new Page<>(page, limit), invitationCode, type, userId)));
    }

    @Override
    public Double selectOrdersMoneyCountByUserId(Long userId, Integer type) {
        return baseMapper.selectOrdersMoneyCountByUserId(userId, type);
    }

    @Override
    public Integer selectUserCountByInvitationCode(String invitationCode, Integer type) {
        return baseMapper.selectUserCountByInvitationCode(invitationCode, type);
    }

    @Override
    public Result selectStaffUserOrdersByTime(Integer page, Integer limit, Long companyId, String startTime, String endTime, String phone, String userName) {
        return Result.success().put("data", baseMapper.selectStaffUserOrdersByTime(new Page<>(page, limit), companyId, startTime, endTime, phone, userName));
    }

    @Override
    public Result selectStaffUserHelpTakesByTime(Integer page, Integer limit, Long companyId, String startTime, String endTime, String phone, String userName) {
        return Result.success().put("data", baseMapper.selectStaffUserHelpTakesByTime(new Page<>(page, limit), companyId, startTime, endTime, phone, userName));
    }

    @Override
    public Integer selectRankingByUserId(Long userId, Long companyId) {
        return baseMapper.selectRankingByUserId(userId, companyId);
    }

    @Override
    public Integer selectOrdersCountByCompany(Long userId) {
        return baseMapper.selectOrdersCountByCompany(userId);
    }

    @Override
    public BigDecimal selectOrdersMoneyByCompany(Long userId) {
        return baseMapper.selectOrdersMoneyByCompany(userId);
    }

    @Override
    public Map<String, Object> selectOrdersCountByStaffUser(Long userId, Long companyId, String taskTime, String time, Integer flag) {
        return baseMapper.selectOrdersCountByStaffUser(userId, companyId, taskTime, time, flag);
    }

    @Override
    public Map<String, Object> selectOrdersMoneyByStaffUser(Long userId, Long companyId, String taskTime, String time, Integer flag) {
        return baseMapper.selectOrdersMoneyByStaffUser(userId, companyId, taskTime, time, flag);
    }

    @Override
    public Map<String, Object> selectOrdersRefundCountByStaffUser(Long userId, Long companyId, String taskTime, String time, Integer flag) {
        return baseMapper.selectOrdersRefundCountByStaffUser(userId, companyId, taskTime, time, flag);
    }

    @Override
    public Map<String, Object> selectOrdersRefundMoneyByStaffUser(Long userId, Long companyId, String taskTime, String time, Integer flag) {
        return baseMapper.selectOrdersRefundMoneyByStaffUser(userId, companyId, taskTime, time, flag);
    }

    @Override
    public Integer selectOrdersCountByStatusAndTime(String time, Integer flag, Integer state) {
        return baseMapper.selectOrdersCountByStatusAndTime(time, flag, state);
    }

    @Override
    public BigDecimal sumOrdersByCreateTime(String time, Integer flag, Integer payWay) {
        return baseMapper.sumOrdersByCreateTime(time, flag, payWay);
    }

    @Override
    public IPage<HashMap<String, Object>> getAgentProfit(Integer page, Integer limit) {
        Page<HashMap<String, Object>> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getAgentProfit(pages);


    }

    @Override
    public IPage<HashMap<String, Object>> getStaffInfo(Integer page, Integer limit, Long companyId,String time,Integer flag) {

        Page<HashMap<String, Object>> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getStaffInfo(pages, companyId, time, flag);


    }

    @Override
    public IPage<HashMap<String, Object>> getShopInfo(Integer page, Integer limit,String time,Integer flag) {
        Page<HashMap<String, Object>> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getShopInfo(pages,time,flag);
    }

    @Override
    public HashMap<String, Object> selectStaffStatistics(Long userId, String startTime, String endTime) {
        HashMap<String, Object> map = new HashMap<>();
        //已完成（接单）
        int takeComplete = orderTakingDao.getOrderByStatus(userId, 2, startTime, endTime);
        QueryWrapper<HelpTake> wrapper = new QueryWrapper<>();
        //已完成（万能任务）
        int helpCompleteCount = takeService.selectHelpTakeCountByUserId(userId, 3, startTime, endTime);
        //待完成（接单）
        int takeWaitComplete = orderTakingDao.getOrderByStatus(userId, 1, startTime, endTime);
        //待完成（万能任务）
        int helpIncompleteCount = takeService.selectHelpTakeCountByUserId(userId, 1, startTime, endTime);
        //已评价（接单）
        int takeEvaluateCount = orderTakingDao.getEvaluateOrder(userId, startTime, endTime);
        //已评价（接单）
        int helpEvaluateCount = takeDao.getEvaluateOrder(userId, startTime, endTime);
        //总收益
        BigDecimal allMoney = orderTakingDao.getAllProfit(userId, startTime, endTime);

        /*Double helpEvaluateScore = takeDao.getEvaluateOrderScore(userId, startTime, endTime);
        Double takeEvaluateScore = orderTakingDao.getEvaluateOrderScore(userId, startTime, endTime);
        Double score = helpEvaluateScore + takeEvaluateScore;
        if (helpEvaluateScore > 0 && takeEvaluateScore > 0) {
            score = (BigDecimal.valueOf(score).divide(BigDecimal.valueOf(2), 2, BigDecimal.ROUND_HALF_DOWN)).doubleValue();
        }*/
        //评分
//        UserEntity entity = userService.getById(userId);
//        UserCertification userCertification = userCertificationService.getOne(new QueryWrapper<UserCertification>().eq("user_id", userId));
        map.put("completeCount", takeComplete + helpCompleteCount);
        map.put("waitCompleteCount", takeWaitComplete + helpIncompleteCount);
        map.put("EvaluateCount", takeEvaluateCount + helpEvaluateCount);
        map.put("allMoney", allMoney);
        UserCertification certification = userCertificationService.getOne(new QueryWrapper<UserCertification>().eq("user_id", userId));
        Double score=0.0;
        if(certification!=null){
            score=certification.getScore();
        }
        map.put("score", score);
        return map;
    }

    @Override
    public IPage<Orders> selectNowDayOrders(Integer page, Integer limit, Long userId) {
        Page<Orders> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return orderTakingDao.selectNowDayOrders(pages, userId);
    }

    @Override
    public Result repairFee(Long userId, Long ordersId, BigDecimal money, Integer payType, Integer orderType, HttpServletRequest request) throws Exception {

        if (orderType == 1) {
            HelpOrder helpOrder = helpOrderService.getById(ordersId);
            if (helpOrder.getStatus() != 3) {
                return Result.error("当前状态无法补费");
            }
        } else {
            Orders orders = baseMapper.selectById(ordersId);
            if (!"1".equals(orders.getState())) {
                return Result.error("当前状态无法补费");
            }
        }
        if (payType == 0) {
            UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
            if (userMoney.getMoney().compareTo(money) >= 0) {
                userMoneyService.updateMoney(2, userId, money);
                return payBack(ordersId, orderType, 0, money,null);
            } else {
                return Result.error("当前余额不足");
            }
            //支付宝
        } else if (payType == 4 || payType == 5) {
            return aliPayController.payMoneyRepairFee(userId, ordersId, money, payType, orderType);
            //微信
        } else if (payType == 1 || payType == 2 || payType == 3) {
            return wxService.payMoneyRepairFee(userId, ordersId, money, payType, orderType,request);
        } else {
            return Result.success("支付参数错误");
        }

    }

    @Override
    public Result payBack(Long orderId, Integer orderType, Integer payType, BigDecimal money,String payOrdersNo) {
        BigDecimal repairMoney;
        String value;
        RepairRecord repairRecord = new RepairRecord();
        /*if (orderType == 1) {
            value = commonInfoService.findOne(120).getValue();

        } else {
            value = commonInfoService.findOne(206).getValue();

        }*/

        //补费用户
        UserEntity userEntity;
        //接收的用户
        UserEntity rideEntity;
        //补费用户明细
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        //接收的用户明细
        UserMoneyDetails rideMoneyDetails = new UserMoneyDetails();
        //订单号
        String orderNo;
        if (orderType == 1) {
            HelpOrder helpOrder = helpOrderService.getById(orderId);
            HelpTake helpTake = takeService.getById(helpOrder.getHelpTakeId());
            orderNo = helpOrder.getOrderNo();
            //补费用户
            userEntity = userService.getById(helpOrder.getUserId());
            //接收的用户
            rideEntity = userService.getById(helpTake.getUserId());
            if(helpOrder.getPaySumMoney()!=null){
                helpOrder.setPaySumMoney(helpOrder.getPaySumMoney().add(money));
            }else{
                helpOrder.setPaySumMoney(helpOrder.getMoney().add(money));
            }
            helpOrderService.updateById(helpOrder);
            repairMoney = money.multiply(rideEntity.getRate());
        } else {
            Orders orders = baseMapper.selectById(orderId);
            orderNo = orders.getOrdersNo();
            //补费用户
            userEntity = userService.getById(orders.getUserId());
            //接收的用户
            rideEntity = userService.getById(orders.getOrderTakingUserId());
            if(orders.getPaySumMoney()!=null){
                orders.setPaySumMoney(orders.getPaySumMoney().add(money));
            }else{
                orders.setPaySumMoney(orders.getPayMoney().add(money));
            }
            baseMapper.updateById(orders);
            repairMoney = money.multiply(rideEntity.getRate());
        }

        userMoneyDetails.setTitle("补费成功,补费订单号:" + orderNo);
        userMoneyDetails.setContent("补费金额:" + money);
        userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        userMoneyDetails.setUserId(userEntity.getUserId());
        userMoneyDetails.setMoney(money);
        userMoneyDetails.setType(2);
        userMoneyDetailsService.save(userMoneyDetails);


        /*userMoneyService.updateMoney(1, rideEntity.getUserId(), repairMoney);
        rideMoneyDetails.setTitle("补费成功,补费订单号:" + orderNo);
        rideMoneyDetails.setContent("补费金额:" + repairMoney);
        rideMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        rideMoneyDetails.setUserId(rideEntity.getUserId());
        rideMoneyDetails.setMoney(repairMoney);
        rideMoneyDetails.setType(1);
        userMoneyDetailsService.save(rideMoneyDetails);*/

        repairRecord.setUserId(userEntity.getUserId());
        repairRecord.setRideId(rideEntity.getUserId());

        repairRecord.setUserName(userEntity.getUserName());
        repairRecord.setRideName(rideEntity.getUserName());

        repairRecord.setPayMoney(money);
        repairRecord.setMoney(repairMoney);
        repairRecord.setOrderNo(orderNo);
        repairRecord.setOrderType(orderType);
        repairRecord.setPayWay(payType);
        repairRecord.setStatus(1);
        repairRecord.setCreateTime(new Date());
        repairRecord.setPayOrdersNo(payOrdersNo);
        repairRecordService.save(repairRecord);
        return Result.success();
    }

    @Override
    public Result refundMoney(Long orderId,BigDecimal money,Integer orderType){
        if(money.doubleValue()<=0){
            return Result.error("请输入正确的退款金额！");
        }
        if (orderType == 1) {
            HelpOrder helpOrder = helpOrderService.getById(orderId);
            //获取当前订单支付金额  再获取补费的金额 判断金额是否大于这个金额
            BigDecimal refundMoney=BigDecimal.ZERO;
            if(helpOrder.getRefundMoney()!=null){
                refundMoney=helpOrder.getRefundMoney();
            }
            BigDecimal ordersMoney = helpOrder.getMoney().subtract(refundMoney);
            BigDecimal sumMoney = ordersMoney;
            List<RepairRecord> list = repairRecordService.list(new QueryWrapper<RepairRecord>().eq("order_no", helpOrder.getOrderNo()).eq("order_type", orderType));
            for (RepairRecord record:list){
                refundMoney=BigDecimal.ZERO;
                if(record.getRefundMoney()!=null){
                    refundMoney=record.getRefundMoney();
                }
                BigDecimal recordMoney = record.getPayMoney().subtract(refundMoney);
                sumMoney=sumMoney.add(recordMoney);
            }
            if(sumMoney.doubleValue()<money.doubleValue()){
                return Result.error("退款金额大于订单金额，请重新输入！");
            }
            //进行退款
            //优先退款订单 之后依次退款补费订单
            BigDecimal subtract = ordersMoney.subtract(money);
            BigDecimal ordersRefundMoney=BigDecimal.ZERO;
            if(subtract.doubleValue()<0){
                ordersRefundMoney=ordersMoney;
            }else{
                ordersRefundMoney=money;
            }
            if(ordersRefundMoney.doubleValue()>0){

                //大于0 则直接用订单退款即可 不足则需要补费订单多笔退款
                if (helpOrder.getPayWay() == null || helpOrder.getPayWay() == 1) {
                    userMoneyService.updateMoney(1, helpOrder.getUserId(), ordersRefundMoney);
                } else if (helpOrder.getPayWay() == 2) {
                    //微信
                    boolean refund = wxService.refund(helpOrder.getOrderNo(), ordersRefundMoney);
                    if (!refund) {
                        return Result.error("退款失败，请联系客服处理！");
                    }
                } else {
                    //支付宝
                    String data = aliPayController.alipayRefund(helpOrder.getOrderNo(), ordersRefundMoney);
                    if (StringUtils.isNotBlank(data)) {
                        log.error(data);
                        JSONObject jsonObject = JSON.parseObject(data);
                        JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                        String code1 = alipay_trade_refund_response.getString("code");
                        if (!"10000".equals(code1)) {
                            return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                        }
                    } else {
                        return Result.error("退款失败！");
                    }
                }



                //退款之后 记录退款金额
                if(helpOrder.getRefundMoney()!=null){
                    helpOrder.setRefundMoney(helpOrder.getRefundMoney().add(ordersRefundMoney));
                }else{
                    helpOrder.setRefundMoney(ordersRefundMoney);
                }
                helpOrderService.updateById(helpOrder);
            }
            BigDecimal subtract1 = money.subtract(ordersRefundMoney);
            if(subtract1.doubleValue()>0){
                //如果大于0 则退款还没退完 继续进行补费退款
                BigDecimal subtract2 = money.subtract(ordersRefundMoney);
                for (RepairRecord record:list){
                    refundMoney=BigDecimal.ZERO;
                    if(record.getRefundMoney()!=null){
                        refundMoney=record.getRefundMoney();
                    }
                    //可退款金额
                    BigDecimal recordMoney = record.getPayMoney().subtract(refundMoney);
                    if(recordMoney.doubleValue()>0){
                        subtract = recordMoney.subtract(subtract2);
                        ordersRefundMoney=BigDecimal.ZERO;
                        if(subtract.doubleValue()<0){
                            ordersRefundMoney=recordMoney;
                        }else{
                            ordersRefundMoney=subtract2;
                        }

                        if (record.getPayWay() == 0) {
                            userMoneyService.updateMoney(1, record.getUserId(), ordersRefundMoney);
                        } else if (record.getPayWay() == 1) {
                            //微信
                            boolean refund = wxService.refund(record.getPayOrdersNo(), ordersRefundMoney);
                            if (!refund) {
                                return Result.error("退款失败，请联系客服处理！");
                            }
                        } else {
                            //支付宝
                            String data = aliPayController.alipayRefund(record.getPayOrdersNo(), ordersRefundMoney);
                            if (StringUtils.isNotBlank(data)) {
                                log.error(data);
                                JSONObject jsonObject = JSON.parseObject(data);
                                JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                                String code1 = alipay_trade_refund_response.getString("code");
                                if (!"10000".equals(code1)) {
                                    return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                                }
                            } else {
                                return Result.error("退款失败！");
                            }
                        }
                        //退款之后 记录退款金额
                        if(record.getRefundMoney()!=null){
                            record.setRefundMoney(record.getRefundMoney().add(ordersRefundMoney));
                        }else{
                            record.setRefundMoney(ordersRefundMoney);
                        }
                        repairRecordService.updateById(record);
                        subtract2 = subtract2.subtract(ordersRefundMoney);
                        if(subtract2.doubleValue()<=0){
                            break;
                        }
                    }
                }
            }
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(helpOrder.getUserId());
            userMoneyDetails.setTitle("[需求订单]单号：" + helpOrder.getOrderNo());
            userMoneyDetails.setContent("已原路退还部分退款："+money);
            userMoneyDetails.setType(1);
            userMoneyDetails.setMoney(money);
            userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
            if(helpOrder.getRefundSumMoney()!=null){
                helpOrder.setRefundSumMoney(helpOrder.getRefundSumMoney().add(money));
            }else{
                helpOrder.setRefundSumMoney(money);
            }
            helpOrderService.updateById(helpOrder);
        } else {
            Orders orders = baseMapper.selectById(orderId);
            //获取当前订单支付金额  再获取补费的金额 判断金额是否大于这个金额
            BigDecimal refundMoney=BigDecimal.ZERO;
            if(orders.getRefundMoney()!=null){
                refundMoney=orders.getRefundMoney();
            }
            BigDecimal ordersMoney = orders.getPayMoney().subtract(refundMoney);
            BigDecimal sumMoney = ordersMoney;
            List<RepairRecord> list = repairRecordService.list(new QueryWrapper<RepairRecord>().eq("order_no", orders.getOrdersNo()).eq("order_type", orderType));
            for (RepairRecord record:list){
                refundMoney=BigDecimal.ZERO;
                if(record.getRefundMoney()!=null){
                    refundMoney=record.getRefundMoney();
                }
                BigDecimal recordMoney = record.getPayMoney().subtract(refundMoney);
                sumMoney=sumMoney.add(recordMoney);
            }
            if(sumMoney.doubleValue()<money.doubleValue()){
                return Result.error("退款金额大于订单金额，请重新输入！");
            }
            //进行退款
            //优先退款订单 之后依次退款补费订单
            BigDecimal subtract = ordersMoney.subtract(money);
            BigDecimal ordersRefundMoney=BigDecimal.ZERO;
            if(subtract.doubleValue()<0){
                ordersRefundMoney=ordersMoney;
            }else{
                ordersRefundMoney=money;
            }
            if(ordersRefundMoney.doubleValue()>0){

                //大于0 则直接用订单退款即可 不足则需要补费订单多笔退款
                if (orders.getPayWay() == null || orders.getPayWay() == 1) {
                    userMoneyService.updateMoney(1, orders.getUserId(), ordersRefundMoney);
                } else if (orders.getPayWay() == 2) {
                    //微信
                    boolean refund = wxService.refund(orders.getOrdersNo(), ordersRefundMoney);
                    if (!refund) {
                        return Result.error("退款失败，请联系客服处理！");
                    }
                } else {
                    //支付宝
                    String data = aliPayController.alipayRefund(orders.getOrdersNo(), ordersRefundMoney);
                    if (StringUtils.isNotBlank(data)) {
                        log.error(data);
                        JSONObject jsonObject = JSON.parseObject(data);
                        JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                        String code1 = alipay_trade_refund_response.getString("code");
                        if (!"10000".equals(code1)) {
                            return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                        }
                    } else {
                        return Result.error("退款失败！");
                    }
                }



                //退款之后 记录退款金额
                if(orders.getRefundMoney()!=null){
                    orders.setRefundMoney(orders.getRefundMoney().add(ordersRefundMoney));
                }else{
                    orders.setRefundMoney(ordersRefundMoney);
                }
                baseMapper.updateById(orders);
            }
            BigDecimal subtract1 = money.subtract(ordersRefundMoney);
            if(subtract1.doubleValue()>0){
                //如果大于0 则退款还没退完 继续进行补费退款
                BigDecimal subtract2 = money.subtract(ordersRefundMoney);
                for (RepairRecord record:list){
                    refundMoney=BigDecimal.ZERO;
                    if(record.getRefundMoney()!=null){
                        refundMoney=record.getRefundMoney();
                    }
                    //可退款金额
                    BigDecimal recordMoney = record.getPayMoney().subtract(refundMoney);
                    if(recordMoney.doubleValue()>0){
                        subtract = recordMoney.subtract(subtract2);
                        ordersRefundMoney=BigDecimal.ZERO;
                        if(subtract.doubleValue()<0){
                            ordersRefundMoney=recordMoney;
                        }else{
                            ordersRefundMoney=subtract2;
                        }

                        if (record.getPayWay() == 0) {
                            userMoneyService.updateMoney(1, record.getUserId(), ordersRefundMoney);
                        } else if (record.getPayWay() == 1) {
                            //微信
                            boolean refund = wxService.refund(record.getPayOrdersNo(), ordersRefundMoney);
                            if (!refund) {
                                return Result.error("退款失败，请联系客服处理！");
                            }
                        } else {
                            //支付宝
                            String data = aliPayController.alipayRefund(record.getPayOrdersNo(), ordersRefundMoney);
                            if (StringUtils.isNotBlank(data)) {
                                log.error(data);
                                JSONObject jsonObject = JSON.parseObject(data);
                                JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                                String code1 = alipay_trade_refund_response.getString("code");
                                if (!"10000".equals(code1)) {
                                    return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                                }
                            } else {
                                return Result.error("退款失败！");
                            }
                        }
                        //退款之后 记录退款金额
                        if(record.getRefundMoney()!=null){
                            record.setRefundMoney(record.getRefundMoney().add(ordersRefundMoney));
                        }else{
                            record.setRefundMoney(ordersRefundMoney);
                        }
                        repairRecordService.updateById(record);
                        subtract2 = subtract2.subtract(ordersRefundMoney);
                        if(subtract2.doubleValue()<=0){
                            break;
                        }
                    }
                }
            }
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setTitle("[服务订单]单号：" + orders.getOrdersNo());
            userMoneyDetails.setContent("已原路退还部分退款："+money);
            userMoneyDetails.setType(1);
            userMoneyDetails.setMoney(money);
            userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
            if(orders.getRefundSumMoney()!=null){
                orders.setRefundSumMoney(orders.getRefundSumMoney().add(money));
            }else{
                orders.setRefundSumMoney(money);
            }

            baseMapper.updateById(orders);
        }
        return Result.success();
    }

    @Override
    public Result refundOrders(Long orderId,Integer orderType){
        if (orderType == 1) {
            HelpOrder helpOrder = helpOrderService.getById(orderId);
            //获取当前订单支付金额  再获取补费的金额 判断金额是否大于这个金额
            BigDecimal refundMoney=BigDecimal.ZERO;
            if(helpOrder.getRefundMoney()!=null){
                refundMoney=helpOrder.getRefundMoney();
            }
            BigDecimal ordersMoney = helpOrder.getMoney().subtract(refundMoney);
            BigDecimal sumMoney = ordersMoney;
            List<RepairRecord> list = repairRecordService.list(new QueryWrapper<RepairRecord>().eq("order_no", helpOrder.getOrderNo()).eq("order_type", orderType));
            for (RepairRecord record:list){
                refundMoney=BigDecimal.ZERO;
                if(record.getRefundMoney()!=null){
                    refundMoney=record.getRefundMoney();
                }
                BigDecimal recordMoney = record.getPayMoney().subtract(refundMoney);
                sumMoney=sumMoney.add(recordMoney);
            }
            BigDecimal money=BigDecimal.ZERO;
            //进行退款
            //优先退款订单 之后依次退款补费订单
            BigDecimal ordersRefundMoney=ordersMoney;
            if(ordersRefundMoney.doubleValue()>0){

                //大于0 则直接用订单退款即可 不足则需要补费订单多笔退款
                if (helpOrder.getPayWay() == null || helpOrder.getPayWay() == 1) {
                    userMoneyService.updateMoney(1, helpOrder.getUserId(), ordersRefundMoney);
                } else if (helpOrder.getPayWay() == 2) {
                    //微信
                    boolean refund = wxService.refund(helpOrder.getOrderNo(), ordersRefundMoney);
                    if (!refund) {
                        return Result.error("退款失败，请联系客服处理！");
                    }
                } else {
                    //支付宝
                    String data = aliPayController.alipayRefund(helpOrder.getOrderNo(), ordersRefundMoney);
                    if (StringUtils.isNotBlank(data)) {
                        log.error(data);
                        JSONObject jsonObject = JSON.parseObject(data);
                        JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                        String code1 = alipay_trade_refund_response.getString("code");
                        if (!"10000".equals(code1)) {
                            return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                        }
                    } else {
                        return Result.error("退款失败！");
                    }
                }



                //退款之后 记录退款金额
                if(helpOrder.getRefundMoney()!=null){
                    helpOrder.setRefundMoney(helpOrder.getRefundMoney().add(ordersRefundMoney));
                }else{
                    helpOrder.setRefundMoney(ordersRefundMoney);
                }
                helpOrderService.updateById(helpOrder);
            }
            money=money.add(ordersRefundMoney);
            for (RepairRecord record:list){
                refundMoney=BigDecimal.ZERO;
                if(record.getRefundMoney()!=null){
                    refundMoney=record.getRefundMoney();
                }
                //可退款金额
                BigDecimal recordMoney = record.getPayMoney().subtract(refundMoney);
                if(recordMoney.doubleValue()>0){
                    ordersRefundMoney=recordMoney;
                    if (record.getPayWay() == 0) {
                        userMoneyService.updateMoney(1, record.getUserId(), ordersRefundMoney);
                    } else if (record.getPayWay() == 1) {
                        //微信
                        boolean refund = wxService.refund(record.getPayOrdersNo(), ordersRefundMoney);
                        if (!refund) {
                            return Result.error("退款失败，请联系客服处理！");
                        }
                    } else {
                        //支付宝
                        String data = aliPayController.alipayRefund(record.getPayOrdersNo(), ordersRefundMoney);
                        if (StringUtils.isNotBlank(data)) {
                            log.error(data);
                            JSONObject jsonObject = JSON.parseObject(data);
                            JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                            String code1 = alipay_trade_refund_response.getString("code");
                            if (!"10000".equals(code1)) {
                                return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                            }
                        } else {
                            return Result.error("退款失败！");
                        }
                    }
                    //退款之后 记录退款金额
                    if(record.getRefundMoney()!=null){
                        record.setRefundMoney(record.getRefundMoney().add(ordersRefundMoney));
                    }else{
                        record.setRefundMoney(ordersRefundMoney);
                    }
                    repairRecordService.updateById(record);
                    money=money.add(ordersRefundMoney);
                }
            }
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(helpOrder.getUserId());
            userMoneyDetails.setTitle("[需求订单]单号：" + helpOrder.getOrderNo());
            userMoneyDetails.setContent("已原路退款："+money);
            userMoneyDetails.setType(1);
            userMoneyDetails.setMoney(money);
            userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
            if(helpOrder.getRefundSumMoney()!=null){
                helpOrder.setRefundSumMoney(helpOrder.getRefundSumMoney().add(money));
            }else{
                helpOrder.setRefundSumMoney(money);
            }
            helpOrderService.updateById(helpOrder);
        } else {
            Orders orders = baseMapper.selectById(orderId);
            //获取当前订单支付金额  再获取补费的金额 判断金额是否大于这个金额
            BigDecimal refundMoney=BigDecimal.ZERO;
            if(orders.getRefundMoney()!=null){
                refundMoney=orders.getRefundMoney();
            }
            BigDecimal ordersMoney = orders.getPayMoney().subtract(refundMoney);
            BigDecimal sumMoney = ordersMoney;
            List<RepairRecord> list = repairRecordService.list(new QueryWrapper<RepairRecord>().eq("order_no", orders.getOrdersNo()).eq("order_type", orderType));
            for (RepairRecord record:list){
                refundMoney=BigDecimal.ZERO;
                if(record.getRefundMoney()!=null){
                    refundMoney=record.getRefundMoney();
                }
                BigDecimal recordMoney = record.getPayMoney().subtract(refundMoney);
                sumMoney=sumMoney.add(recordMoney);
            }
            //进行退款
            //优先退款订单 之后依次退款补费订单
            BigDecimal ordersRefundMoney=ordersMoney;
            if(ordersRefundMoney.doubleValue()>0){

                //大于0 则直接用订单退款即可 不足则需要补费订单多笔退款
                if (orders.getPayWay() == null || orders.getPayWay() == 1) {
                    userMoneyService.updateMoney(1, orders.getUserId(), ordersRefundMoney);
                } else if (orders.getPayWay() == 2) {
                    //微信
                    boolean refund = wxService.refund(orders.getOrdersNo(), ordersRefundMoney);
                    if (!refund) {
                        return Result.error("退款失败，请联系客服处理！");
                    }
                } else {
                    //支付宝
                    String data = aliPayController.alipayRefund(orders.getOrdersNo(), ordersRefundMoney);
                    if (StringUtils.isNotBlank(data)) {
                        log.error(data);
                        JSONObject jsonObject = JSON.parseObject(data);
                        JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                        String code1 = alipay_trade_refund_response.getString("code");
                        if (!"10000".equals(code1)) {
                            return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                        }
                    } else {
                        return Result.error("退款失败！");
                    }
                }



                //退款之后 记录退款金额
                if(orders.getRefundMoney()!=null){
                    orders.setRefundMoney(orders.getRefundMoney().add(ordersRefundMoney));
                }else{
                    orders.setRefundMoney(ordersRefundMoney);
                }
                baseMapper.updateById(orders);
            }
            BigDecimal money=ordersRefundMoney;

            for (RepairRecord record:list){
                refundMoney=BigDecimal.ZERO;
                if(record.getRefundMoney()!=null){
                    refundMoney=record.getRefundMoney();
                }
                //可退款金额
                BigDecimal recordMoney = record.getPayMoney().subtract(refundMoney);
                if(recordMoney.doubleValue()>0){
                    ordersRefundMoney=recordMoney;
                    if (record.getPayWay() == 0) {
                        userMoneyService.updateMoney(1, record.getUserId(), ordersRefundMoney);
                    } else if (record.getPayWay() == 1) {
                        //微信
                        boolean refund = wxService.refund(record.getPayOrdersNo(), ordersRefundMoney);
                        if (!refund) {
                            return Result.error("退款失败，请联系客服处理！");
                        }
                    } else {
                        //支付宝
                        String data = aliPayController.alipayRefund(record.getPayOrdersNo(), ordersRefundMoney);
                        if (StringUtils.isNotBlank(data)) {
                            log.error(data);
                            JSONObject jsonObject = JSON.parseObject(data);
                            JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                            String code1 = alipay_trade_refund_response.getString("code");
                            if (!"10000".equals(code1)) {
                                return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                            }
                        } else {
                            return Result.error("退款失败！");
                        }
                    }
                    //退款之后 记录退款金额
                    if(record.getRefundMoney()!=null){
                        record.setRefundMoney(record.getRefundMoney().add(ordersRefundMoney));
                    }else{
                        record.setRefundMoney(ordersRefundMoney);
                    }
                    repairRecordService.updateById(record);
                    money=money.add(ordersRefundMoney);
                }
            }
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setTitle("[服务订单]单号：" + orders.getOrdersNo());
            userMoneyDetails.setContent("已原路退款："+money);
            userMoneyDetails.setType(1);
            userMoneyDetails.setMoney(money);
            userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
            if(orders.getRefundSumMoney()!=null){
                orders.setRefundSumMoney(orders.getRefundSumMoney().add(money));
            }else{
                orders.setRefundSumMoney(money);
            }
            baseMapper.updateById(orders);
        }
        return Result.success();
    }

    @Override
    public Result selectRefundMoney(Long orderId,Integer orderType){
        if (orderType == 1) {
            HelpOrder helpOrder = helpOrderService.getById(orderId);
            //获取当前订单支付金额  再获取补费的金额 判断金额是否大于这个金额
            BigDecimal refundMoney=BigDecimal.ZERO;
            if(helpOrder.getRefundMoney()!=null){
                refundMoney=helpOrder.getRefundMoney();
            }
            BigDecimal ordersMoney = helpOrder.getMoney().subtract(refundMoney);
            BigDecimal sumMoney = ordersMoney;
            List<RepairRecord> list = repairRecordService.list(new QueryWrapper<RepairRecord>().eq("order_no", helpOrder.getOrderNo()).eq("order_type", orderType));
            for (RepairRecord record:list){
                refundMoney=BigDecimal.ZERO;
                if(record.getRefundMoney()!=null){
                    refundMoney=record.getRefundMoney();
                }
                BigDecimal recordMoney = record.getPayMoney().subtract(refundMoney);
                sumMoney=sumMoney.add(recordMoney);
            }
            return Result.success().put("data",sumMoney);
        }else{
            Orders orders = baseMapper.selectById(orderId);
            //获取当前订单支付金额  再获取补费的金额 判断金额是否大于这个金额
            BigDecimal refundMoney=BigDecimal.ZERO;
            if(orders.getRefundMoney()!=null){
                refundMoney=orders.getRefundMoney();
            }
            BigDecimal ordersMoney = orders.getPayMoney().subtract(refundMoney);
            BigDecimal sumMoney = ordersMoney;
            List<RepairRecord> list = repairRecordService.list(new QueryWrapper<RepairRecord>().eq("order_no", orders.getOrdersNo()).eq("order_type", orderType));
            for (RepairRecord record:list){
                refundMoney=BigDecimal.ZERO;
                if(record.getRefundMoney()!=null){
                    refundMoney=record.getRefundMoney();
                }
                BigDecimal recordMoney = record.getPayMoney().subtract(refundMoney);
                sumMoney=sumMoney.add(recordMoney);
            }
            return Result.success().put("data",sumMoney);
        }
    }



    @Override
    public IPage<HashMap<String, Object>> getStaffOrderList(Integer page, Integer limit, Long userId) {
        Page<HashMap<String, Object>> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getStaffOrderList(pages, userId);
    }

    @Override
    public IPage<HashMap<String, Object>> getStaffUserOrder(Integer page, Integer limit, Long companyId) {
        Page<HashMap<String, Object>> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getStaffUserOrder(pages, companyId);


    }

    @Override
    public HashMap<String, Object> getUserStatistics(String time, Integer flag) {
        HashMap<String, Object> hashMap = new HashMap<>();
        //全部用户
        int allUserCount = baseMapper.getAllUserCount(time, flag);
        //会员用户
        int vipCount = baseMapper.getVipUserCount(time, flag);
        //普通用户
        int generalCount = baseMapper.getUserGeneralCount(time, flag);
        //商家用户
        int shopUserCount = baseMapper.shopUserCount(time, flag, 2, 2);
        //师傅用户
        int workUserCount = baseMapper.shopUserCount(time, flag, 2, 1);
        //员工用户
        int staffUserCount = baseMapper.staffUserCount(time, flag);
        int h5Count = baseMapper.getPlatform(time, flag, "H5");
        int courseCount = baseMapper.getPlatform(time, flag, "小程序");
        int officialCount = baseMapper.getPlatform(time, flag, "公众号");

        hashMap.put("allUserCount", allUserCount);
        hashMap.put("vipCount", vipCount);
        hashMap.put("generalCount", generalCount);
        hashMap.put("shopUserCount", shopUserCount);
        hashMap.put("workUserCount", workUserCount);
        hashMap.put("staffUserCount", staffUserCount);
        hashMap.put("h5Count", h5Count);
        hashMap.put("courseCount", courseCount);
        hashMap.put("officialCount", officialCount);

        return hashMap;
    }

    @Override
    public HashMap<String, Object> getOrderStatusCount(Long userId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        Integer waitService = baseMapper.selectCount(new QueryWrapper<Orders>().eq("isdelete",0).eq("orders_type", 1).eq("state", 1).eq("user_id", userId));
        Integer progress = baseMapper.selectCount(new QueryWrapper<Orders>().eq("isdelete",0).eq("orders_type", 1).eq("state", 4).eq("user_id", userId));
        Integer waitPay = baseMapper.selectCount(new QueryWrapper<Orders>().eq("isdelete",0).eq("orders_type", 1).eq("state", 0).eq("user_id", userId));
        //接单待服务
        hashMap.put("waitService", waitService);
        //接单进行中
        hashMap.put("progress", progress);
        //接单待支付
        hashMap.put("waitPay", waitPay);
        Integer helpWaitPay = helpOrderService.count(new QueryWrapper<HelpOrder>().eq("status", 0).eq("user_id", userId));
        Integer helpWaitService = helpOrderService.count(new QueryWrapper<HelpOrder>().eq("status", 1).eq("user_id", userId));
        Integer helpProgress = helpOrderService.count(new QueryWrapper<HelpOrder>().eq("status", 2).eq("user_id", userId));
        Integer helpWaiting = helpOrderService.count(new QueryWrapper<HelpOrder>().eq("status", 3).eq("user_id", userId));

        //服务待支付
        hashMap.put("helpWaitPay", helpWaitPay);
        //服务待接单
        hashMap.put("helpWaitService", helpWaitService);
        //服务进待服务
        hashMap.put("helpProgress", helpProgress);
        //服务进行中
        hashMap.put("helpWaiting", helpWaiting);
        return hashMap;


    }

    /**
     * 下单播报
     */
    @Override
    public Result orderBroadcast() {
        List<Long> userIds = this.lambdaQuery().eq(Orders::getState, 4)
                .orderByDesc(Orders::getCreateTime)
                .last("limit 10")
                .list()
                .stream().map(Orders::getUserId).collect(Collectors.toList());
        List<OrderBroadcastVo> list = userService.lambdaQuery().in(UserEntity::getUserId, userIds).list().stream().map(it -> {
            OrderBroadcastVo vo = new OrderBroadcastVo();
            vo.setAvatar(it.getAvatar());
            vo.setContent(it.getUserName() + " 刚刚下了订单");
            return vo;
        }).collect(Collectors.toList());
        return Result.success().put("data", list);
    }
}
